<?php
declare(strict_types=1);

namespace Modules\Subject\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Modules\Develop\Support\Generate\Create\Request;
use Modules\Grade\Models\Grade;
use Modules\Subject\Models\Subject;
use Modules\Subject\Http\Requests\SubjectRequest;


class SubjectController extends Controller
{
    public function __construct(
        protected readonly Subject $model
    ){}

    /**
     * @return mixed
     */
    public function index(): mixed
    {
        $result = [];
        $subjects = Subject::query()->get();
        $gradeArr = Grade::query()->where('status',1)->get();

        foreach ($gradeArr as $gradeItem)
        {
            $chdItem = [];
            $chdItem['value'] = $gradeItem['id'];
            $chdItem['label'] = $gradeItem['name'];

            foreach ($subjects as $subject)
            {
                if ($subject['grade_id'] == $gradeItem['id'])
                {
                    $chdItem['children'][] = [
                        'value' => $subject['id'],
                        'label' => $subject['name'],
                    ];
                }
            }

            $result[] = $chdItem;
        }

        return $result;
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(SubjectRequest $request)
    {
        return $this->model->storeBy($request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, SubjectRequest $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function delete(SubjectRequest $request)
    {
        $id = $request->all('id');
        if (isset($id)){
            $subject = Subject::query()->where('id',$id)->first();
            return $subject->delete();
        } else {
            throw new FailedException("删除失败");
        }
    }

    public function add(SubjectRequest $request)
    {
        $data  = [];
        $param = $request->all();

        if (isset($param['name']))
        {
            $data['name'] = $param['name'];
        }

        if (isset($param['grade_id']))
        {
            $data['grade_id'] = $param['grade_id'];
        }

        $subject = Subject::query()->where(['name'=>$data['name'],'grade_id'=>$data['grade_id']])->get();

        if (count($subject))
        {
            throw new FailedException($data['name'].'已存在');
        }

        return $this->model->createBy($data);
    }
}
